<template>
  <div class="box">
    <div
      :fullscreen="true"
      v-loading.lock="loading"
      class="loading-content"
      v-if="loading"
    ></div>
    <div v-else>
      <div class="btnGroup">
        <div
          class="btn"
          :class="activeBtn == 1 ? 'active' : ''"
          @click="activeBtn = 1"
        >
          {{ $t("card") }}
        </div>
        <div
          class="btn"
          :class="activeBtn == 2 ? 'active' : ''"
          @click="activeBtn = 2"
        >
          {{ $t("wallet") }}
        </div>
      </div>
      <div v-if="activeBtn == 1">
        <ul class="list-ul" v-if="list.length > 0">
          <li
            v-for="item of list"
            :key="item.id"
            @click="goPay(item)"
            :class="activeAmount == item.price ? 'active' : ''"
          >
            {{ item.price }} USD
          </li>
          <li class="amountInput">
            <el-input
              v-model="amount"
              type="number"
              :placeholder="$t('amountTips')"
              @input="handleInput"
              @change="handleChange"
            ></el-input>
          </li>
        </ul>
        <div>
          <div class="formStyle">
            <el-form
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
              class="demo-ruleForm"
              label-width="150px"
              label-position="left"
            >
              <el-form-item prop="bank_user_name" :label="$t('name')">
                <el-input
                  v-model="ruleForm.bank_user_name"
                  :placeholder="$t('nameTips')"
                ></el-input>
              </el-form-item>
              <el-form-item prop="bank_name" :label="$t('BankName')">
                <el-input
                  v-model="ruleForm.bank_name"
                  :placeholder="$t('bankNameTips')"
                ></el-input>
              </el-form-item>
              <el-form-item prop="card_number" :label="$t('cardNum')">
                <el-input
                  v-model="ruleForm.card_number"
                  :placeholder="$t('cardNumTips')"
                ></el-input>
              </el-form-item>
              <el-form-item prop="bank_branch" :label="$t('branchName')">
                <el-input
                  v-model="ruleForm.bank_branch"
                  :placeholder="$t('branchNameTips')"
                ></el-input>
              </el-form-item>
              <el-form-item prop="amount" :label="$t('amount')">
                <el-input
                  v-model="ruleForm.amount"
                  type="number"
                  :placeholder="$t('amountTips')"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="submitBtn">
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
              v-loading="loading"
              >{{ $t("submit") }}</el-button
            >
          </div>
        </div>
      </div>
      <div v-if="activeBtn == 2 && is_wallet == 1">
        <ul class="list-ul" v-if="list.length > 0">
          <li
            v-for="item of list"
            :key="item.id"
            @click="goPay(item)"
            :class="activeAmount == item.price ? 'active' : ''"
          >
            {{ item.price }} USD
          </li>
          <li class="amountInput">
            <el-input
              v-model="amount"
              type="number"
              :placeholder="$t('amountTips')"
              @input="handleInput"
              @change="handleChange"
            ></el-input>
          </li>
        </ul>
        <div class="rechargeInfo">
          <div class="balance">
            <h4>{{ $t("walletBalance") }}：{{ available }} {{ coin_name }}</h4>
            <p>{{ $t("rate") }}：1 USDT = 1USD</p>
            <p>
              {{ $t("walletTips1") }}
            </p>
          </div>
          <div class="lookWallet" @click="$router.push('/wallet')">
            {{ $t("lookWallet") }}
          </div>
        </div>
        <div class="rechargeBtn" v-if="isShowWithdraw" v-loading="btnLoading">
          <div class="btn" @click="toWithdraw">{{ $t("toWithdraw") }}</div>
        </div>
      </div>
      <div v-if="activeBtn == 2 && is_wallet == 0">
        <div class="noWallet">
          <h4 class="title">{{ $t("openWallet") }}</h4>
          <el-divider></el-divider>
          <div class="content">
            <el-form
              :model="form"
              label-position="top"
              :rules="walletRules"
              ref="ruleForm"
            >
              <el-form-item :label="$t('walletEmail')" prop="bind_email">
                <el-input
                  v-model="form.bind_email"
                  :placeholder="$t('walletEmailTip')"
                  style="width: 50%"
                ></el-input>
              </el-form-item>
              <el-form-item :label="$t('walletPsd')" prop="bind_password">
                <el-input
                  v-model="form.bind_password"
                  :placeholder="$t('walletPsdTip')"
                  style="width: 50%"
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="openWalletBtn">
              <el-button
                type="primary"
                @click="openWallet('ruleForm')"
                class="openWallet"
                >{{ $t("openWallet") }}</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  httpWithdrawSubmit,
  httpInfo,
  httpWalletBalance,
  httpWalletWithdraw,
  httpWalletBind,
} from "@/http/api";
import { formatMoney } from "@/utils/common";
export default {
  name: "withdrawal",
  props: {
    assetsTotal: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      value: 0,
      ruleForm: {
        amount: "",
      },
      list: [
        {
          price: 100,
        },
        {
          price: 300,
        },
        {
          price: 500,
        },
        {
          price: 1000,
        },
        {
          price: 2000,
        },
        {
          price: 3000,
        },
        {
          price: 5000,
        },
      ],
      activeAmount: "",
      amount: "",
      rules: {
        bank_user_name: {
          required: true,
          message: this.$t("nameTips"),
          trigger: "change",
        },
        card_number: {
          required: true,
          message: this.$t("cardNumTips"),
          trigger: "change",
        },
        bank_name: {
          required: true,
          message: this.$t("bankNameTips"),
          trigger: "change",
        },
        amount: {
          required: true,
          message: this.$t("amountTips"),
          trigger: "change",
        },
        bank_branch: {
          required: true,
          message: this.$t("branchNameTips"),
          trigger: "change",
        },
      },
      assets_available: "",
      loading: false,
      btnLoading: false,
      activeBtn: 1,
      available: 0,
      coin_name: "",
      form: { bind_email: "", bind_password: "" },
      walletRules: {
        bind_email: [
          { required: true, message: "请输入钱包邮箱账号", trigger: "change" },
        ],
        bind_password: [
          { required: true, validator: this.checkPwd, trigger: "blur" },
        ],
      },
      is_wallet: 0,
      isShowWithdraw: false,
    };
  },
  created() {
    // this.getHttpGoodsList();
    this.getHttpInfo();
  },
  methods: {
    formatMoney,
    getBalance() {
      httpWalletBalance().then((res) => {
        this.available = res.data.available || 0;
        this.coin_name = res.data.coin_name || "USD";
      });
    },
    handleInput(value) {
      this.isShowWithdraw = true;
      this.ruleForm.amount = value;
      this.activeAmount = 0;
    },
    handleChange(value) {
      // 如果输入值小于 10，则将其设为 10
      if (value < 10) {
        this.amount = 10;
      } else {
        this.amount = value;
      }
      this.ruleForm.amount = this.amount;
      this.activeAmount = 0;
    },
    async getHttpInfo() {
      this.loading = true;
      let res = await httpInfo();
      this.loading = false;
      if (res.code == 0) {
        this.assets_total = res.data?.diamond || 0;
        this.is_wallet = res.data?.is_wallet || 0;
        this.form.bind_email = res.data?.account_name || "";
      }
      if (this.is_wallet == 1) {
        this.getBalance();
      }
    },
    goPay(item) {
      this.activeAmount = item.price;
      this.ruleForm.amount = item.price;
      this.isShowWithdraw = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (Number(this.ruleForm.amount) > Number(this.assets_total))
            return this.$message.error("Insufficient Balance");
          this.loading = true;
          let params = {
            way: "bank",
            bank_no: this.ruleForm.card_number,
            bank_name: this.ruleForm.bank_name,
            bank_user_name: this.ruleForm.bank_user_name,
            id_number: this.id_number,
            amount: Number(this.ruleForm.amount),
          };
          let res = await httpWithdrawSubmit(params);
          this.loading = false;

          if (res.code == 0) {
            this.$confirm(
              "The review time is 1-3 working days, please be patient",
              "提示",
              {
                confirmButtonText: "ok",
                type: "info",
              }
            )
              .then(() => {
                this.$message({
                  type: "success",
                  message: "Submitted successfully!",
                });
                this.ruleForm = {};
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除",
                });
              });
          } else {
            this.$message.success(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async toWithdraw() {
      // 判断账户余额是否足够提取，不够提示
      if (this.ruleForm.amount > this.assetsTotal) {
        this.$message({
          type: "error",
          dangerouslyUseHTMLString: true,
          message: this.$t("withdrawError"),
          center: true,
          showClose: true,
          iconClass: " ", // 这个会覆盖图标类名，为了实现去掉图标的操作
          customClass: "el-message--error", // 这个是由于上面设置了iconClass会覆盖掉type，所以需要再设置
        });
      } else {
        this.btnLoading = true;
        const res = await httpWalletWithdraw({ amount: this.ruleForm.amount });
        this.btnLoading = false;
        if (res.code == 0) {
          // 调接口  成功 messge提示，否则messagebox提示
          this.$message({
            type: "success",
            dangerouslyUseHTMLString: true,
            message: this.$t("withdrawSuccess", {
              amount: this.ruleForm.amount,
            }),
            center: true,
            showClose: true,
            iconClass: " ", // 这个会覆盖图标类名，为了实现去掉图标的操作
            customClass: "el-message--success", // 这个是由于上面设置了iconClass会覆盖掉type，所以需要再设置
          });
          this.getBalance();
          this.$emit("child-event");
        } else {
          this.$message.error(res.message);
        }
      }
    },
    openWallet(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const res = httpWalletBind(this.form);
          this.is_wallet = res.data?.is_wallet || 0;
          if (this.is_wallet == 1) {
            this.getBalance();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.box {
  position: relative;
  width: 100%;
  min-height: 400px;
}
.loading-content {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.btnGroup {
  padding: 10px 0 10px;
  display: flex;
  justify-content: start;
  align-items: center;
  .btn {
    width: 180px;
    height: 40px;
    background-color: #e6e6e6;
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    margin-right: 10px;
    cursor: pointer;
  }
  .active {
    background-color: #513316;
    color: #fff;
  }
}
.list-ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, 20%);
  justify-content: space-between;
  gap: 10px;
  background: #fff;
  padding: 10px;
  li {
    width: 100%;
    background: #e6e6e6;
    border-radius: 10px;
    padding: 15px;
    text-align: center;
    box-sizing: border-box;
    cursor: pointer;
  }
  .active {
    background: #efcd2e;
    color: #fff;
  }
}
.rechargeInfo {
  padding: 20px 20px 10px;
  margin-top: 10px;
  background: #fff;
  border-radius: 10px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .balance {
    width: 80%;
  }
  .lookWallet {
    width: 120px;
    height: 40px;
    line-height: 40px;
    border: 1px solid #333;
    border-radius: 5px;
    cursor: pointer;
    text-align: center;
  }
  h4 {
    margin-bottom: 15px;
    font-size: 20px;
  }
  p,
  span {
    margin-bottom: 10px;
    color: rgb(127, 127, 127);
  }
}
.rechargeBtn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  .btn {
    width: 180px;
    height: 50px;
    background-color: #513316;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    cursor: pointer;
  }
}
.formStyle {
  margin-top: 15px;
  background: #fff;
  padding: 10px;
}
.submitBtn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  .el-button {
    width: 200px;
    border-radius: 15px;
    background: #dfeaec;
    border: 1px solid #dfeaec;
    color: #333;
    font-size: 18px;
  }
}
.openWalletBtn {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin-top: 40px;
  .openWallet {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 180px;
    height: 40px;
    line-height: 20px;
    background-color: #513216;
    border-radius: 5px;
    font-size: 12px;
    color: #fff;
    margin-left: 5px;
    text-align: center;
    cursor: pointer;
  }
}
.noWallet {
  background-color: #fff;
  height: 100%;
  width: 100%;
  .title {
    padding: 20px 20px 0;
  }
  .content {
    padding: 0 20px 20px;
    background-color: #fff;
  }
  .openWalletBtn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    margin-top: 40px;
    .openWallet {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 180px;
      height: 40px;
      line-height: 20px;
      background-color: #513216;
      border-radius: 5px;
      font-size: 12px;
      color: #fff;
      margin-left: 5px;
      text-align: center;
      cursor: pointer;
    }
  }
}
</style>
